//
//  TYBaseRefreshViewController.h
//
//
//  Created by 黄卫 on 17/2/24.
//  Copyright © 2017年 huangwei. All rights reserved.
//

#import "TYBaseRefreshViewController.h"
#import "GJRefreshGifFooter.h"
#import "GJRefreshGifHeader.h"
#import "TYHttpTools.h"

#define REMOVE_TABLE_FOOTER(table) {if (table.mj_footer.isRefreshing) {\
[table.mj_footer endRefreshing];\
}\
[table.mj_footer removeFromSuperview];\
table.mj_footer = nil;}

#define REMOVE_TABLE_HEADER(table) {if (table.mj_header.isRefreshing) {\
[table.mj_header endRefreshing];\
}\
[table.mj_header removeFromSuperview];\
table.mj_header = nil;}

#define GJ_PSize (10)

@interface TYBaseRefreshViewController ()

@property (nonatomic, strong) NSString *urlKey;

@end

@implementation TYBaseRefreshViewController

#pragma mark LifeCycle

- (void)dealloc
{
    NSLog(@"%s",__func__);
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.pageIndex = 1;
        self.pageNoKey = @"pNo"; //请求页码的key, 默认为"pNo", 暴露出来有的接口为"pageNo"
        self.pageSizeKey = @"pSize";//请求每页记录数的key, 默认为"pSize", 暴露出来有的接口为"pageSize"
        _dataArray = [NSMutableArray new];
    }
    return self;
}

- (void)viewDidLoad
{
	[super viewDidLoad];
    
    [self initRefreshTableview];
}

#pragma mark Network

- (void)refreshStart
{
    _pageIndex=1;
    self.tableState = TableStateRefreshing;
    [self sendRequest];
}

- (void)loadMoreStart
{
    _pageIndex++;
    self.tableState = TableStateLoading;
    [self sendRequest];
}

- (void)sendRequest
{
    [_refreshTableview hideButton];
    WEAKSELF
    [TYHttpTools getRequestNotNeedCache:API(_urlKey) params:[self requestDic] success:^(id returnValue)
    {
        [MBProgressHUD hideLoadingFromWindow];
        [weakSelf handleResponse:returnValue];
    } failure:^(TYHttpError *errorCode) {
        [MBProgressHUD hideLoadingFromWindow];
        if (errorCode) {
            [MBProgressHUD showError:@"网络请求失败" model:NO];
            [weakSelf handleError:errorCode];
        }
    }];
}

- (void)handleResponse:(id)returnValue
{
    if (!returnValue||![returnValue isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    NSInteger code = [returnValue[@"code"] integerValue];
    if (code!=0) {
        [MBProgressHUD showError:returnValue[@"msg"] model:NO];
    }
    else
    {
        [_refreshTableview reloadData];
        
        NSDictionary *data = returnValue[@"data"];
        if (_tableState == TableStateLoading) {
            [_refreshTableview.mj_footer endRefreshing];
            self.tableState = TableStateIdle;
        }
        else if (_tableState == TableStateRefreshing) {
            [_refreshTableview.mj_header endRefreshing];
            self.tableState = TableStateIdle;
        }
        NSArray *arr = data[@"lst"];
        if (_pageIndex == 1 && !isNull(arr)) {
            [_dataArray removeAllObjects];
            [_refreshTableview reloadData];
        }
        if (isNull(arr)) {
            return;
        }
        else if (arr.count==0) {
            REMOVE_TABLE_FOOTER(_refreshTableview);
            if (self.pageIndex>1) {
                self.pageIndex--;
            }
            else
            {
                [_refreshTableview createButtonForState:0 withImage:nil title:nil clickBlock:nil];
            }
        }
        if (arr.count >= 10 && _dataArray.count==0) {
            [self setBaseTableViewFooter];
        }
        if (arr.count > 0 && arr.count < 10 && _dataArray.count==0) {
            REMOVE_TABLE_FOOTER(_refreshTableview);
        }
        
        [self willChangeValueForKey:@"firstRsp"];
        firstRsp = returnValue[@"data"];
        [self didChangeValueForKey:@"firstRsp"];
        
        if ([self respondsToSelector:@selector(handleRspLst:)])
        {
            [self handleRspLst:arr];
        }
        
    }
}

- (void)handleError:(NSError *)error
{
    if (_tableState == TableStateLoading) {
        [_refreshTableview.mj_footer endRefreshing];
        self.tableState = TableStateIdle;
    }
    else if (_tableState == TableStateRefreshing) {
        [_refreshTableview.mj_header endRefreshing];
        self.tableState = TableStateIdle;
    }
    if (error) {
        if (_pageIndex>1) {
            _pageIndex--;
            ((GJRefreshGifFooter *)_refreshTableview.mj_footer).stateLabel.text = @"加载失败";
        }
        else
        {
            if (_dataArray.count==0) {
                WEAKSELF
                [_refreshTableview createButtonForState:1 clickBlock:^{
                    NSLog(@"刷新");
                    [weakSelf refreshStart];
                }];
                [_refreshTableview reloadData];
            }
        }
    }
}

#pragma mark Delegate

#pragma mark Others

- (NSDictionary *)requestDic
{
    NSMutableDictionary *mDic = self.firstPageParams.mutableCopy;
    [mDic setObject:@(_pageIndex) forKey:self.pageNoKey];
    [mDic setObject:@(self.pageSize?:GJ_PSize) forKey:self.pageSizeKey];
    return mDic;
}

- (void)setUrlKey:(NSString *)urlKey firstPageParams:(NSDictionary *)params
{
    _urlKey = urlKey;
    _firstPageParams = [NSMutableDictionary dictionaryWithDictionary:params];
    [self setTableState:TableStateIdle];
    [MBProgressHUD showLoadingOnWindowWithText:@""];
    [self refreshStart];
}

- (void)initRefreshTableview
{
	if (!_refreshTableview)
    {
        _refreshTableview = [UITableView plainTableView];
        [self.view addSubview:_refreshTableview];
    }
}

- (void)setTableState:(TableState)state
{
    _tableState = state;
    if (state == TableStateRefreshing) {
        if (_refreshTableview.mj_footer.isRefreshing) {
            [_refreshTableview.mj_footer endRefreshing];
        }
        _refreshTableview.mj_header.hidden = NO;
        _refreshTableview.mj_footer.hidden = YES;
    }
    else if (state == TableStateLoading) {
        if (_refreshTableview.mj_header.isRefreshing) {
            [_refreshTableview.mj_header endRefreshing];
        }
        _refreshTableview.mj_footer.hidden = NO;
        _refreshTableview.mj_header.hidden = YES;
    }
    else if (state == TableStateIdle) {
        if (!_refreshTableview.mj_header && !self.ishidHeadRefresh) {
            _refreshTableview.mj_header = [GJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshStart)];
        }
        _refreshTableview.mj_header.hidden=NO;
    }
}

- (void)setBaseTableViewFooter
{
    if (!_refreshTableview.mj_footer) {
        
        _refreshTableview.mj_footer = [GJRefreshGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreStart)];
    }
    _refreshTableview.mj_footer.hidden = NO;
}

@end
